<template>
  <div class="mydrawer">
    <el-drawer v-model="drawer.visible" :title="pageTitle" @close="hide">
      <div class="w-full text-[12px] box">
        <Step :step="curStep" />
        <Step1Form
          v-show="curStep === 1"
          :isEdit="props.type === 'edit'"
          :isNewApp="props.type === 'new'"
          ref="Step1FormRef"
          :info="form1Val"
          @getValue="getFormOneValue"
          @changeStep="changeStep"
        />
        <Step2Form v-show="curStep === 2" :isEdit="props.type === 'edit'" ref="Step2FormRef" @getValue="getFormTwoValue" />
      </div>
      <template #footer>
        <div class="w-full">
          <el-button v-hasPermi="['advertisement:account:remove']" @click="hide">取消</el-button>
          <el-button v-hasPermi="['advertisement:account:remove']" type="primary" v-if="curStep === 1" @click="toNext">下一步</el-button>
          <el-button v-hasPermi="['advertisement:account:remove']" type="primary" v-if="curStep === 2" @click="toBackPrev">上一步</el-button>
          <el-button v-hasPermi="['advertisement:account:remove']" type="primary" v-if="curStep === 2" @click="submitData">保存</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import Step from './step.vue';
import Step1Form from './step1Form.vue';
import Step2Form from './step2Form.vue';
import { createWechatApp, getWechatAppInfo, updateWechatApp } from '@/api/advertisement/wechat';
import { ShareRangeVO, ShareRangeQuery, ShareRangeForm, ByteVO } from '@/api/advertisement/byte/types';
import { useAppStore } from '@/store/modules/app';
import { updateWechatAppVO } from '@/api/advertisement/wechat/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

type StepVO = {
  advertiserId: number;
  tagInfo: string;
  curSelectCateInfo: {
    categoryId: number;
    categoryName: string;
  };
  categoryIndex?: number;
  subCategoryIndex?: number;
  thirdCategoryIndex?: number;
};

const appStore = useAppStore();

const props = defineProps<{
  info: updateWechatAppVO | undefined;
  type: 'copy' | 'edit' | 'new';
}>();

const loading = ref(false);

const curStep = ref<1 | 2>(1);

const Step1FormRef = ref();

const Step2FormRef = ref();

const list = ref<ShareRangeVO[]>([]);

const drawer = reactive<DialogOption>({
  visible: false
});
const initForm: ShareRangeForm = {
  status: '0'
};
const data = reactive<PageData<ShareRangeForm, ShareRangeQuery>>({
  form: { ...initForm },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    accountId: undefined,
    instanceId: undefined,
    assetType: 'BYTED_APPLETS'
  },
  rules: {
    status: [{ required: true, message: '授权方式不能为空', trigger: 'blur' }]
  }
});
const { form, queryParams, rules } = toRefs(data);

const total = ref(0);
const pageTitle = ref<'新建' | '编辑' | '复制'>('新建');

const changeStep = (step: 1 | 2) => {
  curStep.value = step;
};

const form1Val = ref<StepVO>();
const form2Val = ref();
const appInfo = ref();

watch(
  () => props.type,
  () => {
    switch (props.type) {
      case 'new':
        pageTitle.value = '新建';
        break;
      case 'edit':
        pageTitle.value = '编辑';
        break;
      case 'copy':
        pageTitle.value = '复制';
        break;
    }
  }
);

const getInfo = async (info: ByteVO) => {
  console.log('🚀 ~ getInfo ~ info:', info);
  try {
    const res = await getWechatAppInfo({
      accountId: info.accountId,
      advertiserId: info.advertiserId
    });
    console.log('🚀 ~ getInfo ~ res:', res);
    //写死第一个
    const reqData = res.rows[0];
    appInfo.value = reqData;
    Step1FormRef.value?.updateForm1Value(reqData);
    Step2FormRef.value?.updateForm2Value(reqData);
  } catch (error) {
    console.log('🚀 ~ getInfo ~ error:', error);
  }
};

const getFormOneValue = (val) => {
  form1Val.value = val;
};
const getFormTwoValue = async (val) => {
  form2Val.value = val;
  if (props.type === 'edit') {
    console.log('123123131231231', props.info);
    const data: updateWechatAppVO = {
      accountId: appStore.accountId,
      advertiserId: form1Val.value.advertiserId,
      remarkMessage: form2Val.value.remarkMessage,
      iconImageUrl: props.info.iconImageUrl || null,
      headerImageUrl: props.info.headerImageUrl || null,
      labels: props.info.labels || null,
      guideText: props.info.guideText || null,
      imagesHorizontalUrl: props.info.imagesHorizontalUrl || null,
      imagesVerticalUrl: props.info.imagesVerticalUrl || null,
      introduction: props.info.introduction || null,
      instanceId: props.info.instanceId,
      tagInfo: form1Val.value.tagInfo
    };
    hide();
    proxy?.$modal.loading('');
    try {
      await updateWechatApp(data);
      proxy?.$modal.msgSuccess('更新成功');
    } finally {
      Step1FormRef.value.reset();
      Step2FormRef.value.reset();
      proxy?.$modal.closeLoading();
      hide();
      changeStep(1);
    }
  } else {
    const data = {
      accountId: appStore.accountId,
      advertiserId: form1Val.value.advertiserId,
      tagInfo: form1Val.value.tagInfo,
      userName: form2Val.value.userName,
      remarkMessage: form2Val.value.remarkMessage,
      path: form2Val.value.path,
      name: form2Val.value.name
      // appPage: {
      //   startPage: form2Val.value.linkTemp.startPage,
      //   startParam: form2Val.value.linkTemp.params,
      //   linkRemark: form2Val.value.linkTemp.remark
      // }
    };
    hide();
    proxy?.$modal.loading('');
    try {
      await createWechatApp(data);
      proxy?.$modal.msgSuccess('添加成功');
    } finally {
      Step1FormRef.value.reset();
      Step2FormRef.value.reset();
      proxy?.$modal.closeLoading();
    }
  }
};
/**
 * 保存数据
 */
const submitData = () => {
  //数据校验通过后，获取表2的数据并通过接口提交
  Step2FormRef.value?.checkRes();
};

/**
 * 跳转下一步
 */
const toNext = () => {
  Step1FormRef.value?.checkRes();
};

/**
 * 返回上一步
 */
const toBackPrev = () => {
  curStep.value = 1;
};

/**
 * 显示
 */
const show = () => {
  drawer.visible = true;
  nextTick(() => {
    if (props.type !== 'new') {
      getInfo(props.info);
    }
  });
};

/**
 * 隐藏
 */
const hide = () => {
  drawer.visible = false;
  reset();
};
const reset = () => {
  Step1FormRef.value?.reset();
};

onMounted(() => {});

defineExpose({ show });
</script>

<style lang="scss" scoped>
::v-deep(.el-drawer__header) {
  margin-bottom: 15px !important;
}
::v-deep(.el-drawer) {
  width: 540px !important;
}
</style>
